package cn.qayy.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanToMapUtils {
	/***
	 * 增强版对象转换成map
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> objectToMap_strong(Object obj) throws Exception {    
        if(obj == null){    
            return null;    
        }   
        Map<String, Object> map = new HashMap<String, Object>();    
        Field[] declaredFields = obj.getClass().getDeclaredFields();    
        for (Field field : declaredFields) {    
            field.setAccessible(true);  
            //通过ID查询，默认要求ID通过空格隔开
            if(field.getName().equals("id")) {
            	//不为空才单作参数传递给后台xml文件
            	if(StringUtil.isNotBlank(field.get(obj)==null?"":field.get(obj).toString())) {
            		String[] strings = field.get(obj).toString().split(" ");
            		List<String> target = new ArrayList<String>();
            		for(int i=0;i<strings.length;i++) {
            			String item = StringUtil.trimAll(strings[i]);
            			if(StringUtil.isNotBlank(item)) {
            				target.add(item);
            			}
            		}
            		//保证参数都是已经除去空格的了
            		map.put(field.getName(), target);  
            	} 
            } else {
            	//不为空才单作参数传递给后台xml文件
            	if(StringUtil.isNotBlank(field.get(obj)==null?"":field.get(obj).toString())) {
            		String[] strings = field.get(obj).toString().split(",");
            		List<String> target = new ArrayList<String>();
            		for(int i=0;i<strings.length;i++) {
            			String item = StringUtil.trimAll(strings[i]);
            			if(StringUtil.isNotBlank(item)) {
            				target.add(item);
            			}
            		}
            		//保证参数都是已经除去空格的了
            		map.put(field.getName(), target);  
            	}
            }
        }    
        return map;  
    }   
	/***
	 * 对象转换成map
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> objectToMap(Object obj) throws Exception {    
		if(obj == null){    
			return null;    
		}   
		Map<String, Object> map = new HashMap<String, Object>();    
		Field[] declaredFields = obj.getClass().getDeclaredFields();    
		for (Field field : declaredFields) {    
			field.setAccessible(true);  
			map.put(field.getName(), field.get(obj));  
		}    
		return map;  
	}   
}
